#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <unistd.h>
#include <math.h>
#include "game.h"
#include "field.h"
#include "ball.h"
#include "player.h"



void set_lost(GAME_STATE* state) {
	state -> status = 2;
}

void set_won(GAME_STATE* state) {
	state -> status = 1;
}

void eat_ball(FIELD* field, int pos) {
	//increase points
	field -> state -> points +=
		field -> balls[pos] -> value * field -> balls[pos] -> value;
	
	//delete ball
	free(field -> balls[pos]);
	field -> ball_count--;
	for (int i = pos; i < field -> ball_count; i++) {
		field[i] = field[i + 1];
	}
	int maxval = log((double) field -> state -> points) * 2 + 1;
	
	//add new ball
	add_ball(field, maxval > 4 ? 4 : maxval);
	redraw_field(field);
}

void play_game(GAME_STATE* state) {
	state -> points = 0;
	state -> status = 0;
	
	FIELD* f = malloc(sizeof(FIELD));
	if (2 * 40 > COLS || 20 > LINES) {
		endwin();
		fprintf(stderr, "Snek: Terminal is to small, must be 80x20 at least\n");
		exit(1);
	}
	init_field(f, 40, 20, state);
	init_player(f -> player , f -> width / 2, f -> height / 2);
	add_ball(f, 1);
	
	redraw_field(f);
	
	fd_set inputs, test_fds;
	struct timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 56667;
	FD_ZERO(&inputs);
	FD_SET(0, &inputs);
	
	char player_tick = 0;
	while(1) {
		if (state -> status) {
			destroy_field(f);
			return;
		}
		
		
		handle_control(f -> player);
		
		test_fds = inputs;
		
		int sel_ret = select(FD_SETSIZE, &test_fds, (fd_set *) 0, (fd_set *) 0, &timeout);
		
		if (sel_ret == 0) {
			player_tick = (player_tick + 1) % 3;
			move_balls(f);
			update_ballpos(f);
			if (!player_tick) {
				move_player(f);
				update_playerpos(f);
			}
			timeout.tv_sec = 0;
			timeout.tv_usec = 50000;
		}
	}
}
